﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;
using CSM.Models;
using CSM.Controllers;

namespace CSM.Views.Wenjuan
{
    public partial class DoQues : System.Web.UI.Page
    {
        CustomDataContext db = new CustomDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["id"] != null)
                {
                    string tempid=Request.QueryString["id"];
                    string querywen = (from a in db.TCrm_WJ_Statistics_Detail where a.StatID == tempid select a.QuestionID).Single();
                    string[] queryarray = querywen.Split(',');
                    var query = from a in db.TCrm_WJ_QuestionBase where queryarray.Contains(a.QuestionID) select a;
                    string str = "<li id=recordsArray_begin ,style=>试卷开始</li>";
                    string str2 = "recordsArray[]=begin&";
                    foreach (var a in query)
                    {
                        str += "<li id=recordsArray_" + a.QuestionID + ">" + a.Title + "</li>";
                        str2 += "recordsArray[]=" + a.QuestionID + "&";
                    }
                    str += "<li id=recordsArray_end ,background-color=#f2f2f2>试卷结束</li>";
                    str2 += "recordsArray[]=end";
                    TextBox_ID.Text = tempid;
                    TextBox_ID.Enabled = false;
                    TextBox_Name.Text = (from a in db.TCrm_WJ_Statistics where a.StatID == tempid select a.StatName).Single().ToString();
                    temp.InnerHtml = str;
                    orderstring.Value = str2;
                }
                BindMyData(0, "");
                int Totals = TotalPageAmount("");
                int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);
                Label_Total.Text = "共" + pages.ToString();
                Label_CurrenPageAndTo.Text = "页，当前第1" + " 页，转到";

            }

        }
        #region 绑定数据及翻页
        private void BindMyData(int PageIndex, string starts)
        {
            int skipAccount = PageIndex * 10;
            var MyQuery = (from a in db.TCrm_WJ_QuestionBase where a.Title.StartsWith(starts)
                           select new
                           {
                               a.QuestionID,
                               Qtype = a.QType == '0' ? "选择题" : "简答题",
                               a.Title,
                           }).Skip(skipAccount).Take(10);
            GridView1.DataSource = MyQuery;
            GridView1.DataBind();

        }

        //查询出当前记录信息的总条数。
        private int TotalPageAmount(string starts)
        {
            int MyQuery = 0;
            MyQuery = (from a in db.TCrm_WJ_QuestionBase where a.Title.StartsWith(starts) select a).Count();
            return MyQuery;
        }


        //点击按钮，执行查询
        protected void MyClick(object sender, EventArgs e)
        {


            int pageIndx = Convert.ToInt32(CurrentPage.Value);
            string starts = "";
            int Totals = TotalPageAmount(starts);



            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);

            Label_Total.Text = "共" + pages.ToString();

            if (typeof(Button).IsInstanceOfType(sender))
            {
                string arg = ((Button)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "first":

                        pageIndx = 0;

                        break;
                    case "gotopage":
                        if (TextBox_PageIndex.Text == "")
                        { pageIndx = 0; }
                        else
                        {
                            int xx = Convert.ToInt32(TextBox_PageIndex.Text);
                            if (xx > pages)
                            { pageIndx = pages - 1; }

                            else
                            { pageIndx = xx - 1; }


                        }
                        break;
                }

            }
            else if (typeof(LinkButton).IsInstanceOfType(sender))
            {

                string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "prev":
                        if (pageIndx > 0)
                        {
                            pageIndx = pageIndx - 1;
                        }
                        break;
                    case "next":
                        if (pageIndx < pages - 1)
                        {
                            pageIndx = pageIndx + 1;
                        }
                        break;
                    case "last":
                        pageIndx = pages - 1;
                        break;
                    case "first":
                        pageIndx = 0;
                        break;
                }

            }

            CurrentPage.Value = pageIndx.ToString();  //对保存页码状态信息的隐藏字段进行赋值。保存当前页码。
            Label_CurrenPageAndTo.Text = "页，当前第" + (pageIndx + 1).ToString() + " 页，转到";

            BindMyData(pageIndx, starts);

        }

        #endregion

        protected void Button_Submit_Click(object sender, EventArgs e)
        {
            string stateid = TextBox_ID.Text;
            string finalstring="";
            if (orderstring.Value != "" && orderstring.Value != "recordsArray[]=begin&recordsArray[]=end")
            {
                string submitstring = orderstring.Value.Replace("recordsArray[]=", ",").Replace("&", "");
                int start = submitstring.IndexOf("begin") + 6;
                int end = submitstring.IndexOf("end");
                finalstring = submitstring.Substring(start, end - start - 1);
            }
            if (Request.QueryString["id"] == null)
            {
                TCrm_WJ_Statistics myrow = new TCrm_WJ_Statistics();
                myrow.CreateTime = DateTime.Now;
                myrow.UserID = Session[SystemVars.sysSessionUserId].ToString();
                myrow.StatID = TextBox_ID.Text;
                myrow.StatName = TextBox_Name.Text;
                db.TCrm_WJ_Statistics.InsertOnSubmit(myrow);
                TCrm_WJ_Statistics_Detail mynew = new TCrm_WJ_Statistics_Detail();
                mynew.StatID = TextBox_ID.Text;
                mynew.QuestionID = finalstring;
                db.TCrm_WJ_Statistics_Detail.InsertOnSubmit(mynew);
            }
            else
            {
                var myEditQuery = (from a in db.TCrm_WJ_Statistics where a.StatID == Request.QueryString["id"] select a).Single();
                myEditQuery.CreateTime=DateTime.Now;
                myEditQuery.UserID = Session[SystemVars.sysSessionUserId].ToString();
                myEditQuery.StatID = TextBox_ID.Text;
                myEditQuery.StatName = TextBox_Name.Text;
                var EditQuery = (from a in db.TCrm_WJ_Statistics_Detail where a.StatID == Request.QueryString["id"] select a).Single();
                EditQuery.StatID = TextBox_ID.Text;
                EditQuery.QuestionID = finalstring;
            }
            try
                {
                    db.SubmitChanges();
                    MakeHtml();
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('增加成功'); </script>");
                    Response.Redirect("MakeWenjuan.aspx");
                }
            catch
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('增加失败'); </script>");
            }

        }
        protected void Button_Browse_Click(object sender, EventArgs e)
        {
            string user = txtUser.Text;
            BindMyData(0, user);
        }

        //将问卷写入到html文件。
        private void MakeHtml()
        {
            string tempid = TextBox_ID.Text;
            string[] query = (from a in db.TCrm_WJ_Statistics_Detail where a.StatID == tempid select a.QuestionID).Single().ToString().Split(',');
            var query2 = from a in db.TCrm_WJ_QuestionBase where query.Contains(a.QuestionID) select a;
            int len = query2.Count();
            string[] temp1 = new string[len + 1];
            string[] temp2 = new string[len + 1];
            string str = "";
            int i = 1;
            foreach (var a in query2)
            {
                temp1[i] = a.Title;
                str += "<div class='cnt'><h3>" + i + "、" + a.Title + "</h3>";
                str += "<ul class='" + i + "'>";
                var query3 = from b in db.TCrm_WJ_QuestionBase_Detail where b.QuestionID == a.QuestionID select b;
                int j = 1;
                foreach (var c in query3)
                {
                    string tempthis = c.OptionLabel;
                    str += "<li><span>&nbsp;</span><label><input type='radio' name='is0' value='" + j + "'/>" + tempthis + "</label></li>";
                    temp2[i] += c.OptionLabel + "/";
                    j++;
                }
                str += "<input type=text id='" + i + "'/></ul></div>";
                i++;
            }
            StringBuilder htmltext = new StringBuilder();
            try
            {
                using (StreamReader sr = new StreamReader(Server.MapPath("template.html")))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        htmltext.Append(line);
                    }
                    sr.Close();
                }
            }

            catch
            {
                Response.Write("读取文件错误");
            }
            htmltext.Replace("$htmlformat[0]", str);
            htmltext.Replace("'", "\"");
            try
            {
                using (StreamWriter sw = new StreamWriter(Server.MapPath("html/"+tempid + ".html"), false, System.Text.Encoding.GetEncoding("UTF-8")))
                {
                    sw.WriteLine(htmltext);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch
            {
                Response.Write("The file could not be wirte:");
            } 
        }

    }
}
